import 'package:enterprise_v6_app/app/components/common_selection/common_selection_view.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_audioplayers.dart';
import 'package:enterprise_v6_app/app/components/dialog/custom_tape_sheet.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/hazard_investigation_code.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/base_risk_object_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/base_risk_unit_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_currency_arrange_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class ReportingHiddenDangersController extends GetxController {
  /// 录音key
  final GlobalKey<CustomAudioplayersState> globalKey = GlobalKey();

  /// 流程模板实体
  ProcessListEntity entity = ProcessListEntity();

  /// 隐患排查流程部署实体
  ProcessCurrencyArrangeEntity arrangeEntity = ProcessCurrencyArrangeEntity();

  /// 隐患排查流程节点信息
  List<ProcessNodesEntity> nodeList = [];

  @override
  void onInit() {
    super.onInit();
    getProcessRecordByProcessEncoding();
  }

  /// 根据流程唯一编码查询流程详情
  /// todo processEncoding 后端提供的 隐患排查 唯一编码字段,目前为写死
  Future<void> getProcessRecordByProcessEncoding() async {
    //根据流程唯一编码查询流程详情
    final res = await HttpUtil().generateGetRequest<ProcessListEntity>(Interface.getProcessRecordByProcessEncoding, queryParameters: {
      'processEncoding': HazardInvestigationCode.processEncoding,
    }).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        entity = result.data!;
        entity.id = '';
        arrangeEntity.rtCertificateField = entity;
        getNode();
      } else {
        Get.back();
        AppToast.showError('获取作业票流程信息失败');
      }
    });
  }

  /// 根据流程唯一编码查询所有节点
  Future<void> getNode() async {
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(Interface.getNode, queryParameters: {
      'processEncoding': entity.processEncoding!,
    }).execute();
    res.onSuccess((result) {
      nodeList = result.data ?? [];
      for (var node in nodeList) {
        node.id = '';
      }
      arrangeEntity.processNodes = nodeList;
    });
  }

  /// 选择隐患确认人
  void selectReportingPersonnel() {
    Get.toNamed(AppRoutes.personnelDepartmentTreePage, arguments: {
      'title': '隐患确认人',
      'type': '3',
      'organizationalInterface': Interface.getDepartmentTree,
      'personnelInterface': Interface.getUserByAdministrationList,
    })?.then((value) {
      if (value != null) {
        final List<DepartmentUserEntity> userList = value as List<DepartmentUserEntity>;
        arrangeEntity.confirmUserId = userList[0].id;
        arrangeEntity.confirmBy = userList[0].nickname;
        update();
      }
    });
  }

  /// 选择对象
  void selectObject() {
    Get.to(CommonSelectionPage<BaseRiskObjectEntity>(title: '风险分析对象选择'), arguments: {
      // 'queryParameters': {},
      'interfaceUrl': Interface.getObjectAllByCompanyCode,
      'searchName': 'objectName',
    })?.then((value) {
      //如果不为空则设置信息
      if (value != null) {
        final BaseRiskObjectEntity entity = value[0] as BaseRiskObjectEntity;
        arrangeEntity.riskObjectName = entity.riskObjectName;
        arrangeEntity.riskObjectId = entity.id;
        arrangeEntity.riskUnitName = '';
        arrangeEntity.riskUnitId = '';
        update();
      }
    });
  }

  /// 单元选择
  void selectUnit() {
    if (arrangeEntity.riskObjectId!.isEmpty) {
      AppToast.showWarning('请先选择风险分析对象');
      return;
    }
    Get.to(CommonSelectionPage<BaseRiskUnitEntity>(title: '风险分析单元选择'), arguments: {
      'queryParameters': {'objectId': arrangeEntity.riskObjectId},
      'interfaceUrl': Interface.getUnitAllById,
      'searchName': 'unitName',
    })?.then((value) {
      //如果不为空则设置信息
      if (value != null) {
        final BaseRiskUnitEntity entity = value[0] as BaseRiskUnitEntity;
        arrangeEntity.riskUnitName = entity.riskUnitName;
        arrangeEntity.riskUnitId = entity.id;
        update();
      }
    });
  }

  /// 录音
  void onTapTape() {
    CustomTapeSheet(
      onCallBack: (url) {
        arrangeEntity.dangerVoice!.add(url);
        globalKey.currentState?.initData();
        update();
      },
    ).showBottomSheetDialog(isDismissible: false);
  }

  /// 录音删除回调
  void playersCallBack(List<String> urls) {
    arrangeEntity.dangerVoice!.clear();
    arrangeEntity.dangerVoice!.addAll(urls);
    update();
  }

  /// 确定提交
  Future<void> confirm() async {
    if (arrangeEntity.confirmUserId!.isEmpty || arrangeEntity.confirmBy!.isEmpty) {
      AppToast.showWarning('请选择隐患确认人!');
      return;
    }
    if (arrangeEntity.riskObjectId!.isEmpty) {
      AppToast.showWarning('请选择风险分析对象!');
      return;
    }
    if (arrangeEntity.dangerRecordDesc!.isEmpty) {
      AppToast.showWarning('请输入隐患描述!');
      return;
    }
    if (arrangeEntity.dangerImages!.isEmpty) {
      AppToast.showWarning('请拍摄图片!');
      return;
    }

    //流程部署(隐患上报)
    final res = await HttpUtil()
        .generatePostRequest<List<ProcessNodesEntity>>(
          Interface.processLedgerProcessArrange,
          data: arrangeEntity.toJson(),
        )
        .execute();
    //成功
    res.onSuccess((result) {
      Get.back();
      AppToast.showWarning('隐患上报成功!');
    });
  }
}
